<template>
  <a-modal
    title="新建"
    :width="1024"
    :visible="visible"
    :confirmLoading="loading"
    @ok="modalOk"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-row>
          <a-col :span="12">
            <a-form-item v-show="model && model.id > 0" label="主键ID">
              <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
            </a-form-item>
            <a-form-item v-show="!(model && model.id > 0)" label="开票信息">
              <a-button @click="toSelectRecords" type="primary">选择开票信息</a-button>
              <!-- <a-input v-decorator="['id', { initialValue: 0 }]" disabled /> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="发票流水号">
              <a-input v-decorator="['fpqqlsh', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.fpqqlsh}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="发票抬头">
              <a-input v-decorator="['buyerName', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.buyerName}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="买方银行账号">
              <a-input v-decorator="['account', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.account}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="货物名称">
              <a-input v-decorator="['goodsName', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.goodsName}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="发票总额">
              <a-input type="number" step="0.01" v-decorator="['totalPrice', {rules: [{required: true, message: '请输入发票总额'}], initialValue: model.totalPrice}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="发票状态">
              <a-input v-decorator="['submitState', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.submitState}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开票人">
              <a-input v-decorator="['member.name', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.member && model.member.name}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="Token">
              <a-input v-decorator="['token', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.token}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="订单标识">
              <a-input v-decorator="['orderNo', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.orderNo}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="请求json">
              <a-input v-decorator="['dataString', {rules: [{required: true, min: 1, message: '请输入至少五个字符的规则描述！'}], initialValue: model.dataString}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="添加时间"
            >
              <a-date-picker
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                v-decorator="['addtime', {rules: [{required: true, message: '请选择时间'}], initialValue: moment(model.addtime)}]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="份数">
              <a-input v-decorator="['count', {rules: [{required: true, min: 1, message: '请输入份数'}], initialValue: model.count}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户">
              <a-input style="cursor: pointer;" @click="toSelectCustomer" v-decorator="['customerName', {rules: [{required: true, min: 1, message: '请输选择客户'}], initialValue: model.customerName}]" />
              <a-input hidden style="cursor: pointer;" @click="toSelectCustomer" v-decorator="['customerId', {rules: [{required: true, min: 1, message: '请输选择客户'}], initialValue: model.customerId || ''}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="地区">
              <a-cascader
                v-decorator="['AdministrativeRegion', {rules: [{type: 'array', required: true, min: 1, message: '请输选择地区'}], initialValue: model.administrativeRegion || ['']}]"
                :options="administrativeRegionList"
                placeholder="请选择地区"
                @change="onRegionChange" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <select-record @OnSelect="OnSelect" :visible="selectVisible" :model="this.model" @cancel="()=>{this.selectVisible=false}" @ok="modalOk" />
    <select-customer @OnSelect="OnCustomerSelect" :visible="selectCustomerVisible" :model="this.model" @cancel="()=>{this.selectCustomerVisible=false}" @ok="modalOk" />
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addRecord, getStationRecord, putRecord, getAdministrativeRegionList } from '@/api/manage'
import moment from 'moment'
import SelectRecord from './SelectRecord'
import SelectCustomer from './SelectCustomer'
const fields = ['id']

export default {
  name: 'RecordForm',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        // xs: { span: 24 }
        sm: { span: 8 }
      },
      wrapperCol: {
        // xs: { span: 24 }
        sm: { span: 15 }
      }
    }
    return {
      administrativeRegionList: [],
      selectCustomerVisible: false,
      selectVisible: false,
      columns: [
        {
          title: '#',
          dataIndex: 'id'
        },
        {
          title: '详细地址',
          dataIndex: 'delivery.detailedAddress'
        },
        {
          title: '订阅类型',
          dataIndex: 'delivery.subscriptionType'
        },
        {
          title: '投递人员',
          dataIndex: 'delivery.member.name'
        },
        {
          title: '份数',
          dataIndex: 'delivery.subscriptionCount'
        },
        {
          title: '收订员',
          dataIndex: 'delivery.subScriptioner'
        },
        {
          title: '状态',
          dataIndex: 'delivery.submitState'
        }
      ],
      loadData: (parameter) => {
        return getStationRecord({ recordId: this.model.id }).then(res => {
          return {
            data: res.data,
            totalCount: parseInt(res.headers['x-count']),
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          }
        })
      },
      form: this.$form.createForm(this)
    }
  },
  components: {
    SelectRecord,
    SelectCustomer
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    const _self = this
    getAdministrativeRegionList().then(res => {
      // this.administrativeRegionList = res.data
      this.administrativeRegionToTree(res.data)
      console.log(res)
    }).catch(e => {
      console.error(e)
    })
    this.$watch('model', () => {
      if (this.visible) {
        if (this.model && this.model.administrativeRegion && !(this.model.administrativeRegion instanceof Array)) {
          this.model.administrativeRegion = this.model.administrativeRegion.split('/')
        }
        // _self.$refs.table.refresh(true)
        // this.$refs.table.refresh(false)
        this.form = this.$form.createForm(this)
        _self.$nextTick(() => {
          this.model && this.form.setFieldsValue(pick(this.model, fields))
          // this.$refs.table.refresh(true)
        })
      }
    })
  },
  methods: {
    onRegionChange (value) {
      console.log(value.join('/'))
    },
    administrativeRegionToTree (list) {
      const rootList = []
      list.forEach((item, index) => {
        item.value = item.districtName
        item.label = item.districtName
        item.key = item.id
        if (item.parentId === 0) {
          rootList.push(item)
        }
      })
      console.log(rootList)
      rootList.forEach(item => {
        item.children = this.jsonToTree(item, list)
      })
      this.administrativeRegionList = rootList
    },
    jsonToTree (item, data) {
      const childrens = []
      data.forEach(_item => {
        if (_item.parentId === item.id) {
          childrens.push(_item)
          const _children = this.jsonToTree(_item, data)
          if (_children.length < 1) {
            return
          }
          _item.children = _children
        }
      })
      return childrens
    },
    OnCustomerSelect (record) {
      this.selectCustomerVisible = false
      console.log(record.id)
      console.log(record.name)
      this.form.setFieldsValue({
        'customerId': record.id + '',
        'customerName': record.name
      })
      this.model.customerId = record.id + ''
    },
    OnSelect (record) {
      this.selectVisible = false
      this.form.setFieldsValue({
        'buyerName': record.title,
        'account': record.bankAccount,
        'goodsName': record.spec
      })
      this.model.bueryName = record.title
    },
    moment,
    modalOk () {
      this.form.validateFieldsAndScroll((errors, values) => {
        console.log(values)
        if (!errors) {
          delete values.id
          values.AdministrativeRegion = values.AdministrativeRegion.join('/')
          if (this.model && this.model.id) {
            putRecord(this.model.id, values).then(res => {
              this.$emit('ok')
            })
          } else {
            addRecord(values).then(res => {
              this.$emit('ok')
            })
          }
        }
      })
    },
    toSelectCustomer () {
      this.selectCustomerVisible = true
    },
    toSelectRecords () {
      this.selectVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
